package com.zzb.framework.validator.aop;

import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.validator.annotation.ValidatorEnabled;
import com.zzb.framework.validator.ret.ValidatorRet;
import com.zzb.framework.validator.util.ValidatorRetUtils;
import com.zzb.framework.validator.util.ValidatorUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * 表单验证aop
 * Created by zhangzhenbin on 2016/12/22.
 */
@Aspect
@Component
public class ValidatorAspect {
    Logger logger = LoggerFactory.getLogger(ValidatorAspect.class);

    @Around(value = "@annotation(validatorEnabled)")
    public Object validateProcess(ProceedingJoinPoint joinPoint, ValidatorEnabled validatorEnabled) throws Throwable {
        ValidatorRet validate = new ValidatorRet();
        validate.setStatus(ValidatorRet.SUCCESS);

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //获取切面方法所有的参数名称
        Object[] args = joinPoint.getArgs();
        Parameter[] parameters = method.getParameters();
        if (ArrayUtils.isNotEmpty(parameters)) {
            for (int i = 0; i < parameters.length; i++) {
                Class type = parameters[i].getType();
                ValidatorRet argValidatorRet = ValidatorUtils.validate(args[i], type);
                if(!argValidatorRet.isSuccess()){
                    ValidatorRetUtils.addMessagesMap(validate,argValidatorRet.getValidatorMsgs());
                }
            }
        }
        if(! validate.isSuccess()){
            Class<?> returnType = method.getReturnType();
            if(returnType.equals(BaseResponse.class)){
                return new BaseResponse<>(BaseResponse.FAIL, ValidatorRetUtils.getErrorMessages(validate),validate.getValidatorMsgs());
            } else if(returnType.equals(Map.class)){
                return new BaseResponse<>(BaseResponse.FAIL, ValidatorRetUtils.getErrorMessages(validate),validate.getValidatorMsgs()).toMap();
            } else {
                logger.error("[" + method.getName() + "]表单验证返回结果失败，切面方法的返回值类型必须是BaseResponse或Map");
            }
        } else {
            logger.info("[" + method.getName() + "]表单验证通过");
        }
        return joinPoint.proceed();//执行切面方法
    }
}
